import React, { useCallback, useState } from 'react';
import { useDropzone } from 'react-dropzone';
import { ActiveState } from '../models/misc';
import { getToken} from '../login/loginApi'; 

const MultiFileUpload = ({
  modalState,
  setModalState,
}: {
  modalState: ActiveState;
  setModalState: (state: ActiveState) => void;
}) => {
  const [files, setFiles] = useState<File[]>([]);
  const [uploading, setUploading] = useState<boolean>(false);

  const onDrop = useCallback((acceptedFiles: File[]) => {
    setFiles((prevFiles) => [...prevFiles, ...acceptedFiles]);
  }, []);

  // 限制上传文件类型
  const { getRootProps, getInputProps, isDragActive } = useDropzone({
    onDrop,
    multiple: true,
    accept: {
      'text/plain': ['.txt'],
      'application/pdf': ['.pdf'],
      'application/msword': ['.doc'], // 对于旧的.doc文件
      'application/vnd.openxmlformats-officedocument.wordprocessingml.document': ['.docx'], // 对于.docx文件
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': ['.xlsx'], // 对于.xlsx文件
    },
  });

  const removeFile = (fileName: string) => {
    setFiles(files.filter((file) => file.name !== fileName));
  };

  const uploadFiles = async () => {
   
    const apiHost = import.meta.env.VITE_API_HOST || '';
    const formData = new FormData();
    files.forEach(file => {
      formData.append('file[]', file); // 根据后端接口要求，使用'file[]'作为键名
    });

    // 如果文件列表为空，则不执行上传操作
    if (files.length === 0) {
      alert('还未选择任何文件');
      return;
    }

    setUploading(true);
    
    // 添加额外的表单字段
    formData.append('title', '直接上传的文件');
    formData.append('tags', JSON.stringify(["brain science"]));

    if (getToken()=="" ){
      alert("Please login first")
      return
    }
    
    console.log(getToken());
  
    try {
    
      const response = await fetch(apiHost+'/documents/direct/upload', { // 更新请求的URL
        method: 'POST',
        body: formData,
        headers: {
          "Authorization": `Bearer ${getToken()}`
        },
      });
  
      if (response.ok) {
        alert('文件上传成功');
        setFiles([]);
      } else {
        alert('文件上传失败');
      }
    } catch (error) {
      alert('上传过程中发生错误');
      console.error('上传过程中发生错误', error);
    } finally {
      setUploading(false);
      setModalState('INACTIVE');
    }
  };

  // 如果modalState不是'ACTIVE'，则不显示弹窗
  if (modalState !== 'ACTIVE') {
    return null;
  }

  return (
    <div className="fixed inset-0 z-50 overflow-auto bg-black bg-opacity-40 flex justify-center items-center">
      <div className="container mx-auto mt-10 max-w-xl bg-white rounded shadow-lg p-5">
        <div {...getRootProps()} className={`p-10 border-dashed border-2 border-gray-300 rounded-md cursor-pointer ${isDragActive ? 'bg-gray-100' : 'bg-white'}`}>
          <input {...getInputProps()} />
          {isDragActive ? (
            <p className="text-gray-500">放开鼠标以上传文件</p>
          ) : (
            <p className="text-gray-500">拖拽文件到这里，或点击选择文件</p>
          )}
        </div>
        <ul className="mt-5">
          {files.map((file, index) => (
            <li key={index} className="flex justify-between items-center mt-3 p-2 border-b border-gray-200">
              <span className="text-sm text-gray-600">{file.name} - {file.size} bytes</span>
              <button onClick={() => removeFile(file.name)} className="bg-red-500 hover:bg-red-700 text-white font-bold py-1 px-2 rounded">
                删除
              </button>
            </li>
          ))}
        </ul>
        <button onClick={uploadFiles} className="mt-5 bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded" disabled={uploading}>
          {uploading ? '正在上传...' : '上传文件'}
        </button>
        <button onClick={() => setModalState('INACTIVE')} className="mt-5 ml-4 bg-gray-500 hover:bg-gray-700 text-white font-bold py-2 px-4 rounded">
          取消
        </button>
      </div>
    </div>
  );
};

export default MultiFileUpload;